package com.unf.edu.rms.controller.users;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.unf.edu.rms.controller.userlogin.UserLoginController;
import com.unf.edu.rms.controller.validation.UserValidator;
import com.unf.edu.rms.dao.Faculty;
import com.unf.edu.rms.dao.UserLogin;
import com.unf.edu.rms.dao.UserRole;
import com.unf.edu.rms.service.FacultyService;
import com.unf.edu.rms.service.UsersService;
import com.unf.edu.rms.util.Password;
import com.unf.edu.rms.util.RMSConstants;

@Controller
public class UsersController extends RMSBaseController{
	@Autowired
	private UsersService usersService;
	@Autowired
	private FacultyService facultyService;
	@Autowired
	private UserLoginController userLoginController;
	
	@RequestMapping("/viewUsersList")
	public String viewUsersList(Model model) {
		if(userLoginController.checkValidateSession()==0 || userLoginController.checkValidateSession()==2){
			return "redirect:Dashboard.html";
		}
		List<UserLogin> usersList = usersService.viewUserTable();
		model.addAttribute("usersList", usersList);
		return RMSConstants.USERS_LIST_VIEW;
	}
	
	@RequestMapping(value = "/viewNewUser", method = RequestMethod.POST)
	public String viewNewUser(@ModelAttribute("userLogin") UserLogin userLogin,Model model) {
		if(userLoginController.checkValidateSession()==0 || userLoginController.checkValidateSession()==2){
			return "redirect:Dashboard.html";
		}
		
		List<UserRole> userRoleList = usersService.viewUserRoleTable();
		model.addAttribute("userRoleList", userRoleList);
		
		List<Faculty> facultyList = facultyService.getFacultyList();
		Map<Integer,String> facultyMap = new HashMap<Integer, String>();
		for(Faculty faculty:facultyList)
		{
			facultyMap.put(faculty.getFacultyId(),faculty.getFirstName()+" "+faculty.getLastName());
		}
		model.addAttribute("facultyList", facultyMap);
		
		return RMSConstants.ADD_USER_VIEW;
	}
	
	@RequestMapping(value = "/addNewUser", method = RequestMethod.POST)
	public String addNewUser(@ModelAttribute("userLogin") UserLogin userLogin,BindingResult bindingResult,Model model) throws Exception {
		System.out.println("UsersController.addNewUser()=========="+userLogin);
		
		System.out.println("UsersController.addNewUser()========facultyId======="+userLogin.getFaculty().getFacultyId());
		userLogin.setFirstTimeLogin("Y");
		
		UserValidator userValidator = new UserValidator();
		userValidator.validate(userLogin, bindingResult);
		
		//Check username of userLogin against the userLogin usernames in the database
		//Check that the faculty member Id isn't used twice
		//Add error to bindResult for validation
		List<UserLogin> userList = usersService.viewUserTable();
		
		for(int i = 0; i < userList.size(); i++){
			UserLogin user = userList.get(i);
			if(user.getUserName().equalsIgnoreCase(userLogin.getUserName())){
				bindingResult.rejectValue("userName", "error.username.duplicate");
			}
			if(user.getFaculty().getFacultyId().equals(userLogin.getFaculty().getFacultyId())){
				bindingResult.rejectValue("faculty.facultyId", "error.facultyId.duplicate");
			}
		}
		
		if(!bindingResult.hasErrors()){
			
			Password pw = new Password();
			userLogin.setPassword(pw.encryptPassword(userLogin.getPassword()));
			usersService.addNewUser(userLogin);
			return "redirect:viewUsersList.html";
		}
		else{
			List<UserRole> userRoleList = usersService.viewUserRoleTable();
			model.addAttribute("userRoleList", userRoleList);
			
			List<Faculty> facultyList = facultyService.getFacultyList();
			Map<Integer,String> facultyMap = new HashMap<Integer, String>();
			for(Faculty faculty:facultyList)
			{
				facultyMap.put(faculty.getFacultyId(),faculty.getFirstName()+" "+faculty.getLastName());
			}
			model.addAttribute("facultyList", facultyMap);
			return RMSConstants.ADD_USER_VIEW;
		}
	}
	

	@RequestMapping(value = "/viewExistingUser", method = RequestMethod.POST)
	public String viewExitingUser(@RequestParam(required=true) int userLoginId,Model model) {
		
		if(userLoginController.checkValidateSession()==0 || userLoginController.checkValidateSession()==2 || userLoginController.checkValidateSession()==3){
			return "redirect:Dashboard.html";
		}
		
		UserLogin userLogin = usersService.getUserById(userLoginId);
		model.addAttribute("userLogin",userLogin);
		
		List<UserRole> userRoleList = usersService.viewUserRoleTable();
		model.addAttribute("userRoleList", userRoleList);
		
		List<Faculty> facultyList = facultyService.getFacultyList();
		Map<Integer,String> facultyMap = new HashMap<Integer, String>();
		for(Faculty faculty:facultyList)
		{
			facultyMap.put(faculty.getFacultyId(),faculty.getFirstName()+" "+faculty.getLastName());
		}
		model.addAttribute("facultyList", facultyMap);
		
		return RMSConstants.ADD_USER_VIEW;
	}
	
	@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
	public String updateUser(@RequestParam(required=true) int userLoginId,@ModelAttribute("userLogin") UserLogin userLogin,BindingResult bindingResult,Model model) throws Exception {
		
		UserValidator userValidator = new UserValidator();
		userValidator.validate(userLogin, bindingResult);
		
		List<UserLogin> userList = usersService.viewUserTable();
		
		for(int i = 0; i < userList.size(); i++){
			UserLogin user = userList.get(i);
			if(user.getUserLoginId()!=userLoginId){
				if(user.getUserName().equalsIgnoreCase(userLogin.getUserName())){
					bindingResult.rejectValue("userName", "error.username.duplicate");
				}
				if(user.getFaculty().getFacultyId().equals(userLogin.getFaculty().getFacultyId())){
					bindingResult.rejectValue("faculty.facultyId", "error.facultyId.duplicate");
				}
			}
			else{
				int currentUserId = userLoginController.getSessionUserId();
				System.out.println("User Ids: " + currentUserId + "  " + userLoginId);
				if(currentUserId==userLoginId && user.getUserRole().getUserRoleId()==1  && userLogin.getUserRole().getUserRoleId()!=1){
					bindingResult.rejectValue("userRole.userRoleId", "error.userRole.superadminblock");
				}
			}
		}
		
		if(!bindingResult.hasErrors()){
			userLogin.setUserLoginId(userLoginId);
			UserLogin checkUserPw = usersService.getUserById(userLoginId);
			if(!checkUserPw.getPassword().equals(userLogin.getPassword())){
				Password pw = new Password();
				userLogin.setPassword(pw.encryptPassword(userLogin.getPassword()));
			}
			usersService.updateUser(userLogin);
			return "redirect:viewUsersList.html";
		}
		else{
			List<UserRole> userRoleList = usersService.viewUserRoleTable();
			model.addAttribute("userRoleList", userRoleList);
			
			List<Faculty> facultyList = facultyService.getFacultyList();
			Map<Integer,String> facultyMap = new HashMap<Integer, String>();
			for(Faculty faculty:facultyList)
			{
				facultyMap.put(faculty.getFacultyId(),faculty.getFirstName()+" "+faculty.getLastName());
			}
			model.addAttribute("facultyList", facultyMap);
			return RMSConstants.ADD_USER_VIEW;
		}
	}
}
